package com.kirk.cts.core.base.pagination.mybatis;

import com.kirk.cts.core.base.pagination.PaginationSupport;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.LinkedList;
import java.util.List;


/**
 * <p> MyBatisPersistenceImpl.java </p>
 *
 * @version 1.0.0
 * @Author kirkliu
 * @Date 2020-08-31 23:01
 * @Description IBatis服务接口实现类
 */
public class MyBatisPersistenceImpl extends SqlSessionDaoSupport implements MyBatisPersistence {
    protected Logger logger = Logger.getLogger(this.getClass());


    @Override
    public int save(String sqlId, Object parameterObject) {
        return getSqlSession().insert(sqlId, parameterObject);
    }


    @Override
    public int modify(String sqlId, Object parameterObject) {
        return getSqlSession().update(sqlId, parameterObject);
    }


    @Override
    public int remove(String sqlId, final Object parameterObject) {
        return getSqlSession().delete(sqlId, parameterObject);
    }


    @Override
    public Object get(String sqlId, final Object parameterObject) {
        return getSqlSession().selectOne(sqlId, parameterObject);
    }


    @SuppressWarnings("unchecked")
    @Override
    public PaginationSupport<?> getPaginatedResult(String sqlId, final Object parameterObject, int offset, int limit) {
        Integer count = null;
        try {
            count = (Integer) getSqlSession().selectOne(sqlId + "_COUNT", parameterObject);
        } catch (Exception e) {
            String msg = "配置文件中不存在COUNT语句或发生其它例外,无法执行总数统计. SqlMap id:" + sqlId;
            logger.warn(msg, e);
        }
        int tmpOffset = (offset < 0 ? 0 : offset);
        int tmpLimit = (limit <= 0 ? 1 : limit);

        if (count == null || count.intValue() <= 0) {
            logger.trace("执行COUNT后,返回的结果数为0,表示该SQL执行无结果数据返回.因此提前终止其数据查询并立即返回空集.");
            return new PaginationSupport(new LinkedList(), 0, tmpOffset, tmpLimit);
        }
        List<?> resultList = getSqlSession().selectList(sqlId, parameterObject, new RowBounds(tmpOffset, tmpLimit));
        return new PaginationSupport(resultList, count.intValue(), tmpOffset, tmpLimit);
    }


    @Override
    public List<?> getList(String sqlId, Object parameterObject) {
        return getSqlSession().selectList(sqlId, parameterObject);
    }

}
